using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.Permissions.Commands;
using Identity.Application.Permissions.Interfaces;
using MediatR;

namespace Identity.Application.Permissions.CommandHandlers;

public class UpdatePermissionCommandHandler : IRequestHandler<UpdatePermissionCommand, Result>
{
    private readonly IPermissionsRepository _permissionsRepository;
    private readonly IApiPermissionBindingReadService _apiPermissionBindingReadService;
    private readonly IUnitOfWork _unitOfWork;
    public UpdatePermissionCommandHandler(IPermissionsRepository permissionsRepository,IApiPermissionBindingReadService apiPermissionBindingReadService, IUnitOfWork unitOfWork)
    {
        _permissionsRepository = permissionsRepository;
        _apiPermissionBindingReadService = apiPermissionBindingReadService;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result> Handle(UpdatePermissionCommand request, CancellationToken cancellationToken)
    {
        var permission = await _permissionsRepository.GetPermissionByIdAsync(request.Id);
        if (permission == null) return Result.Failure("权限不存在");
        permission.ChangeName(request.name);
        permission.ChangeKey(request.key);
        permission.ChangeDescription(request.description);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
        var apipermission = await _apiPermissionBindingReadService.GetBindingsByPermissionKeyAsync(permission.Key);
        var serviceName = apipermission.ToList().FirstOrDefault()?.fromServiceName;
        return Result.Success(new PermissionDto(permission.Id, permission.Name, permission.Key, permission.Description, serviceName, !string.IsNullOrWhiteSpace(serviceName)));
    }
}